#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void hex_encode(const char* filein,const char* fileou, int mod) {
	FILE *fdi, *fdo;
	int i=0, c;

	fdi=strcmp(filein,"stdin") ?fopen(filein,"rb"):stdin;
	if (!fdi) return -1; /* Error while opening input file */
	fdo=strcmp(fileou,"stdout")?fopen(fileou,"wt"):stdout;
	if (!fdo) return -2; /* Error while opening output file */

	while ((c=fgetc(fdi))!=EOF) {
	  fprintf(fdo,"%02x",c);
	  if (mod && !((++i)%mod)) 
		fputc('\n',fdo);
	 }
	if (!mod || i%mod)
		fputc('\n',fdo);
		
	fclose(fdi);
	fclose(fdo);
}

int hex_decode(const char* filein,const char* fileou) {
	FILE *fdi, *fdo;
	int i=0, c;

	fdi=strcmp(filein,"stdin") ?fopen(filein,"rb"):stdin;
	if (!fdi) return -1; /* Error while opening input file */
	fdo=strcmp(fileou,"stdout")?fopen(fileou,"wt"):stdout;
	if (!fdo) return -2; /* Error while opening output file */

	while (fscanf(fdi,"%02x", &c)!=EOF) {
		fputc(c,fdo);
	}
	
	fclose(fdi);
	fclose(fdo);
}

int main(int a, char* b[]) {
	if (strcmp(b[1],"-x")==0)
		hex_encode(b[2],b[3], atoi(b[4]));
	else if (strcmp(b[1],"-b")==0)
		hex_decode(b[2],b[3]);
	else printf("Invalid option");
	
	return 0;
}

